# encoding: utf-8
require "china_city/engine"

module ChinaCity
  PATTERN = /(\d{2})(\d{2})(\d{2})/

  class << self
    def list(province='all', city=nil)
      parse
      if province.blank?
        []
      elsif province == 'all'
        @provinces
      elsif city.blank?
        @cities[province]
      else
        @districts["#{province}#{city}"]
      end
    end

    def province(code)
      match(code)[1].ljust(6, '0')
    end

    def city(code)
      id_match = match(code)
      "#{id_match[1]}#{id_match[2]}".ljust(6, '0')
    end

    def district(code)
      code[0..5].rjust(6,'0')
    end

    def parse
      return if @parsed
      json = JSON.parse(File.read("#{Rails.root}/db/areas.json"))

      @provinces = []
      province_hash = {}

      json['province'].each do |p|
        @provinces << p['text']
        province_hash[p['id']] = p['text']
      end

      @cities = {}
      city_hash = {}

      json['city'].each do |c|
        province = province_hash[province(c['id'])]
        @cities[province] ||= []
        @cities[province] << c['text']
        city_hash[c['id']] = c['text']
      end

      @districts = {}
      json['district'].each do |d|
        province = province_hash[province(d['id'])]
        city = city_hash[city(d['id'])]

        @districts["#{province}#{city}"] ||= []
        @districts["#{province}#{city}"] << d['text']
      end
      @parsed = true
    end

    def match(code)
      code.match(PATTERN)
    end
  end
end
